import { Controller, Post, UseGuards, Req, Body, Delete, Get, Query } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { InjectModel } from 'nestjs-typegoose';
import { Qrcode } from "@libs/db/models/qrcode.models"
import { gen } from "js-shortid"
import { AddQrcodeDto } from "./dto/addqrcode.dto"
import { DelqrcodeDto, SelqrcodeDto } from "./dto/delqrcode.dto"
import { Setqrcode } from "./dto/setqrcode.dto"
import { Getqrcode } from './dto/getqrcode.dto';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { Subcode } from '@libs/db/models/subcode.models';
import { readdirSync, unlinkSync, rmdirSync } from 'fs';
import { IP } from '@libs/db/models/ip.models';


@Controller('qrcode')
@ApiTags('活码模块')
@ApiBearerAuth()
@UseGuards(AuthGuard("jwt"))
export class QrcodeController {
    public imagepath: string = "public/uploads/"
    constructor(
        @InjectModel(Subcode) public SubcodeModel: ModelType<Subcode>,
        @InjectModel(Qrcode) public qrcodeModel: ModelType<Qrcode>,
        @InjectModel(IP) private IPModel: ModelType<IP>
    ) { }


    @ApiOperation({ summary: "新增活码" })
    @Post("addqrcode")
    async addqrcode(@Req() req, @Body() body: AddQrcodeDto): Promise<object> {
        let shortid: string = gen({ salts: 1, interval: 10 });
        let time = Math.floor(Date.now() / 1000);
        let qrcode = await this.qrcodeModel.create({
            ...body, shortid: shortid, userid: req.user._id, todayscann: 0, totalscann: 0, time
        });
        return qrcode
    }


    @ApiOperation({ summary: "删除单条活码" })
    @Delete("delqrcode")
    async delqrcode(@Body() body: DelqrcodeDto, @Req() req): Promise<object> {
        const select = await this.qrcodeModel.findOne({ _id: body.id, userid: req.user._id })
        const deletes = await this.qrcodeModel.deleteOne({ _id: body.id, userid: req.user._id })
        this.SubcodeModel.deleteMany({ qrcodeid: body.id, userid: req.user._id }).then()
        this.IPModel.deleteMany({ qrcode: body.id }).then()
        setTimeout(() => {
            try {
                const path = __dirname + "/" + this.imagepath + select.shortid
                const files = readdirSync(path)
                for (var i = 0; i < files.length; i++) {
                    unlinkSync(path + "/" + files[i])
                }
                rmdirSync(path)
            } catch (error) { }
        }, 100)

        return deletes
    }


    @ApiOperation({ summary: "删除全部活码" })
    @Delete("allcode")
    async delqrcodeall(@Req() req): Promise<object> {
        const select = await this.qrcodeModel.find({ userid: req.user._id })
        let deletes = await this.qrcodeModel.deleteMany({ userid: req.user._id })
        this.SubcodeModel.deleteMany({ userid: req.user._id }).then()
        this.IPModel.deleteMany({ userid: req.user._id }).then()
        setTimeout(() => {
            try {
                select.forEach((item) => {
                    const path = __dirname + "/" + this.imagepath + item.shortid
                    const files = readdirSync(path)
                    for (var i = 0; i < files.length; i++) {
                        unlinkSync(path + "/" + files[i])
                    }
                    rmdirSync(path)
                })
            } catch (error) { }
        }, 100)

        return deletes
    }


    @ApiOperation({ summary: "修改活码" })
    @Post("setqrcode")
    async setqrcode(@Body() body: Setqrcode, @Req() req): Promise<object> {
        let setqrcode = await this.qrcodeModel.updateOne({ _id: body.id, userid: req.user._id }, body)
        await this.SubcodeModel.updateMany({ qrcodeid: body.id, userid: req.user._id }, { restrictedmode: body.restrictedmode })
        return setqrcode
    }


    @ApiOperation({ summary: "查询全部活码" })
    @Post("getcodeall")
    async getcodeall(@Body() body: Getqrcode, @Req() req): Promise<object> {
        let count = await this.qrcodeModel.countDocuments({ userid: req.user._id })
        let getcodeall = await this.qrcodeModel.find({ userid: req.user._id }).skip((body.page - 1) * 10).limit(10).sort({ '_id': -1 });
        return { total: count, date: getcodeall }
    }


    @ApiOperation({ summary: "查询单条活码" })
    @Get("getqrcode")
    async getqrcode(@Query() query: SelqrcodeDto, @Req() req): Promise<object> {
        let getqrcode = await this.qrcodeModel.find({ codename: query.codename, userid: req.user._id })
        return getqrcode
    }


    @ApiOperation({ summary: "展示次数归零" })
    @Get("clear")
    async Clear(@Query() query: DelqrcodeDto, @Req() req): Promise<object> {
        await this.qrcodeModel.updateMany({ _id: query.id, userid: req.user._id }, { todayscann: 0, totalscann: 0, todayclick: 0, totalclick: 0 })
        await this.SubcodeModel.updateMany({ qrcodeid: query.id, userid: req.user._id }, { impression: 0, identifynum: 0, todayclick: 0, totalclick: 0 })
        this.IPModel.deleteMany({ userid: req.user._id, qrcode: query.id }).then()
        return { code: 200, msg: '清除成功' }
    }

}
